const webpack = require('webpack')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base')
const MiniCssExtractPlugin = require('mini-css-extract-plugin') // 提取css并异步加载css
const TerserPluger = require('terser-webpack-plugin') // 压缩js
const CleanWebpackPlugin = require('clean-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const Analyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin  // bundle体积监控和分析
const sizePlugin = require('size-plugin') // 显示模块增量 调优

module.exports = merge.smart(baseWebpackConfig, {
  mode: 'production',
  output: {
    // 由JS或者CSS间接请求资源的路径。指定这部分间接资源的请求位置
    publicPath: '/'  // 斜杠代表路径以此时host.name为基础的
  },
  module: {
    rules: [{
      test: /\.(css|scss)$/,
      use: [
        {
          // 用了这个，可以再生产环境取代style-loader插入页面的作用
          loader: MiniCssExtractPlugin.loader,
        }, 
        // sec
        {
          loader: 'css-loader',
          options: {
            sourceMap: true
          }
        },
        // fir
        {
          loader: 'sass-loader',
          options: {
            sourceMap: true
          }
        },
        // 前置处理
        'postcss-loader' // postcss-loader要求必须有一个单独的配置文件 
      ],
      exclude: /node_modules/
    }]
  },
  optimization: {
    minimizer: [
      new TerserPluger({ // 4.0之后UglifyJsPlugin功能移植到了optimization.minimize
        test: /\.js(\?.*)?$/i,
        sourceMap: true,
        exclude: /node_modules/
      }), 
      new MiniCssExtractPlugin({
        filename: 'css/[name]@[chunkhash].css',
        chunkFilename: 'css/[id].css'
      }),
      new OptimizeCSSAssetsPlugin({ // 压缩提取之后的css
        assetNameRegExp: /\.css$/g,
        canPrint: true
      })
    ],
    splitChunks: { // 代码拆分-提取公共模块，会形成一个公共模块的vendorJs
      chunks: 'all'
    } 
  },
  // devtool: 'source-map', // 生产环境中用UglifyjsWebpackPlugin压缩之后，目前只支持source-map
  plugins: [
    new CleanWebpackPlugin.CleanWebpackPlugin({ verbose: true }),

    new MiniCssExtractPlugin({ // 生产环境用它替换 style-loader
      filename: 'css/[name]@[hash].css',
      chunkFilename: 'css/[id].css'
    }),
    new sizePlugin(),
    new Analyzer()

  ]
})